﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.WorkingManagement.TeamSet
{
    public partial class UpdateTeamSetForm : DevExpress.XtraEditors.XtraForm
    {
        public delegate void UpdateTeamSetDelegate();
        public event UpdateTeamSetDelegate UpdateTeamSetEvent;

        private TeamSetModel _currentTeamSet;

        public UpdateTeamSetForm(TeamSetModel teamSet)
        {
            InitializeComponent();
            _currentTeamSet = teamSet;
            InitTeamTypeComboBox();
        }

        // 初始化团队类型下拉框数据
        private async void InitTeamTypeComboBox()
        {
            try
            {
                // 初始化下拉框显示格式
                comboBoxEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

                // 获取团队类型列表
                var teamTypeList = await GetAllTeamTypes();
                if (teamTypeList != null && teamTypeList.Count > 0)
                {
                    // 设置数据源，使用Dictionary存储Id和Name
                    var dataSource = new Dictionary<string, string>();
                    dataSource.Add("", "请选择"); // 添加一个空选项

                    foreach (var item in teamTypeList)
                    {
                        dataSource.Add(item.id.ToString(), item.teamTypeName);
                    }

                    // 绑定到下拉框
                    comboBoxEdit1.Properties.Items.Clear();
                    foreach (var item in dataSource)
                    {
                        comboBoxEdit1.Properties.Items.Add(new ComboBoxItem { Value = item.Key, Display = item.Value });
                    }

                    // 数据反显
                    DisplayTeamSetData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载团队类型数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 数据反显方法
        private void DisplayTeamSetData()
        {
            if (_currentTeamSet != null)
            {
                textEdit1.Text = _currentTeamSet.teamSetCode;
                textEdit2.Text = _currentTeamSet.teamSetName;
                textEdit3.Text = _currentTeamSet.teamLeader;
                memoEdit1.Text = _currentTeamSet.remark;

                // 设置团队类型下拉框选中项
                string teamTypeIdStr = _currentTeamSet.teamTypeId.ToString();
                foreach (ComboBoxItem item in comboBoxEdit1.Properties.Items)
                {
                    if (item.Value == teamTypeIdStr)
                    {
                        comboBoxEdit1.SelectedItem = item;
                        break;
                    }
                }
            }
        }

        // 获取所有团队类型数据
        private async Task<List<TeamTypeItem>> GetAllTeamTypes()
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var response = await HttpClientHelper.RequestUrl(RequestType.get, MethodGolab.SHOW_DEFECT + "?PageIndex=1&PageSize=1000");
                    //序列化
                    var result = JsonConvert.DeserializeObject<TeamTypeResponse<TeamTypeItem>>(response);
                    if (result.code == 200)
                    {
                        return result.items;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"获取团队类型列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return new List<TeamTypeItem>();
            }
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(textEdit1.Text) ||
                string.IsNullOrWhiteSpace(textEdit2.Text) ||
                comboBoxEdit1.SelectedIndex <= 0) // 检查是否选择了有效的团队类型
            {
                XtraMessageBox.Show("请填写必要信息（团队编码、团队名称、团队类型）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string TeamTypeId = "";
            if (comboBoxEdit1.SelectedItem is ComboBoxItem selectedItem)
            {
                TeamTypeId = selectedItem.Value;
            }

            var data = JsonConvert.SerializeObject(new
            {
                id = _currentTeamSet.id,
                teamSetCode = textEdit1.Text.Trim(),
                teamTypeId = TeamTypeId,
                teamTypeName = "",
                teamSetName = textEdit2.Text.Trim(),
                teamLeader = textEdit3.Text.Trim(),
                remark = memoEdit1.Text.Trim(),
            });

            try
            {
                var response = await HttpClientHelper.RequestUrl(RequestType.post, MethodGolab.POST_SETUPDATE, data);
                var resultData = JsonConvert.DeserializeObject<TeamSetResponse<TeamSetModel>>(response);

                if (resultData.code == 200)
                {
                    XtraMessageBox.Show("修改成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (UpdateTeamSetEvent != null)
                        UpdateTeamSetEvent.Invoke();
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show($"修改团队设置失败：{resultData.message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}